package com.wondertek.poms.service.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IEquityNodeService;
import com.wondertek.poms.core.service.IEquityTreeService;
import com.wondertek.poms.core.service.IProductGroupService;
import com.wondertek.poms.dao.po.EquityNode;
import com.wondertek.poms.dao.po.EquityTree;
import com.wondertek.poms.dao.po.ProductGroup;
import com.wondertek.poms.dao.pojo.EquityNodePojo;
import com.wondertek.poms.dao.repo.IPrdContDao;
import com.wondertek.poms.dao.vo.EquityNodeMinVo;
import com.wondertek.poms.service.vo.EquityNodeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.beans.Transient;
import java.util.List;
import java.util.Optional;

@Api(value = "EquityNodeController", description = "权益树节点管理")
@RequestMapping(value="/equity-node")
@RestController
public class EquityNodeController {

    @Autowired
    private IEquityNodeService equityNodeService;
    @Autowired
    private IEquityTreeService equityTreeService;
    @Autowired
    private IProductGroupService productGroupService;
    @Autowired
    private IPrdContDao prdContDao;


    @PostMapping(value = "/add")
    @ResponseBody
    @MethodLog(module = "权益节点添加",insertDB=true)
    public ResultBean add(@RequestBody EquityNodeVo equityNodeVo){
        List<String> messageList = ValidateFilter.getFilterMessage(equityNodeVo, Constants.VALIDATE_DEFAULT);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }
        if(checkDate(equityNodeVo)){
            return ResultBean.error("节点名重复时产品组必须一致！");
        }

        EquityNode equityNode=new EquityNode();
        BeanUtils.copyProperties(equityNodeVo,equityNode);
        equityNode.setDeleteStatus(0);
        nodeAddHierarchy(equityNode);
        //权益节点编码
        if (equityNode.getParentId() != 0) {
            EquityTree tree = equityTreeService.get(equityNode.getTreeId());
            if (tree == null) {
                return ResultBean.error(MessageCodes.get(MessageCodes.M980011));
            }
            String treeName = tree.getEquityTreeName();
            equityNode.setEquityNodeId(treeName + "@" + equityNode.getName());
        }
        EquityNode.putTimeAndUser(equityNode);
        equityNodeService.save(equityNode);

        //权益树深度的增加后的更新
        try {
            equityTreeService.updateTreeDepth(equityNode.getTreeId());
        } catch (Exception e) {
            equityNodeService.deleteById(equityNode.getId());
            String msg="新增节点失败！";
            return ResultBean.error(msg);
        }
        return ResultBean.ok();
    }

    @ApiOperation("获取权益节点列表")
    @GetMapping(value = "/list")
    @ResponseBody
    public ResultBean list(EquityNodeMinVo vo,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "20") int rows,
                           @RequestParam(defaultValue = "UPDATE_TIME") String sidx,
                           @RequestParam(defaultValue = "desc") String sord){
        if(vo.getEquityNodeId()==null && vo.getName()==null){
            return ResultBean.ok(equityNodeService.findAll());
        }
        EquityNode equityNode=new EquityNode();
        BeanUtils.copyProperties(vo,equityNode);
        return ResultBean.ok(equityNodeService.findAll(equityNode,page,rows,sidx,sord));
    }

    @ApiOperation("获取权益节点列表")
    @GetMapping(value = "/list-for-select")
    @ResponseBody
    public ResultBean list(){
        return ResultBean.ok(equityNodeService.findForSelect());
    }

    @ApiOperation("通过子节点id获取子节点信息")
    @GetMapping(value = "/get")
    @ResponseBody
    public ResultBean getEquityNodeByNodeId(String id){
        if (StrUtil.isBlank(id)) {
            return ResultBean.error(MessageCodes.get(MessageCodes.M980203));
        }
        EquityNode equityNode=equityNodeService.get(Convert.toLong(id));
        return ResultBean.ok(equityNode);
    }

    @PutMapping(value = "/edit")
    @ResponseBody
    @MethodLog(module = "权益节点编辑",insertDB=true,opterate = 2)
    public ResultBean edit(@RequestBody EquityNodeVo equityNodeVo){
        List<String> messageList = ValidateFilter.getFilterMessage(equityNodeVo, Constants.VALIDATE_DEFAULT);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }
        EquityNode equityNode = equityNodeService.get(equityNodeVo.getId());
        if(!equityNodeVo.getName().equals(equityNode.getName())){
            if(checkDate(equityNodeVo)){
                return ResultBean.error("节点名重复时产品组必须一致！");
            }
        }
        if("0".equals(equityNode.getStatus())){
            return ResultBean.error("该节点为启用状态，不能编辑！");
        }
        BeanUtils.copyProperties(equityNodeVo,equityNode);

        EquityNode.putTimeAndUser(equityNode);
        equityNodeService.save(equityNode);
        EquityTree equityTree = equityTreeService.get(equityNode.getTreeId());
        equityTree.setActiveStatus("2");
        equityTreeService.save(equityTree);
        return ResultBean.ok();
    }

    @DeleteMapping(value = "/delete")
    @ResponseBody
    @MethodLog(module = "权益节点删除",insertDB=true,opterate = 3)
    public ResultBean delete(String id){
        if (StrUtil.isBlank(id)) {
            return ResultBean.error(MessageCodes.get(MessageCodes.M980203));
        }
        /*String msg=equityNodeService.deleteByNodeId(Convert.toLong(id));
        if(StrUtil.isNotBlank(msg)){
            return ResultBean.error(msg);
        }*/
        EquityNode equityNode = equityNodeService.get(Convert.toLong(id));
        if(equityNode !=null){
            if(equityNode.getStatus().equals("0")){
                String msg="该节点处于启用状态，不能删除!";
                return ResultBean.error(msg);
            }
        }
        equityNode.setDeleteStatus(1);
        equityNodeService.save(equityNode);
        //权益树深度的更新
        try {
            equityTreeService.updateTreeDepth(equityNode.getTreeId());
        } catch (Exception e) {
            equityNode.setDeleteStatus(0);
            equityNodeService.save(equityNode);
            return ResultBean.error("删除节点失败！");
        }
        return ResultBean.ok();
    }

    @GetMapping(value = "/get-all-product-group")
    @ResponseBody
    public ResultBean getAllProductGroup(){
        ProductGroup productGroup=new ProductGroup();
        productGroup.setStatus("0");
        List<ProductGroup> list=productGroupService.findAll(productGroup);
        return ResultBean.ok(list);
    }

    @GetMapping(value = "/update-status")
    @ResponseBody
    @MethodLog(module = "权益节点状态编辑",insertDB=true,opterate = 2)
    public ResultBean updateStatus(Long id,String status){
        EquityNode equityNode=equityNodeService.get(id);
        if("1".equals(status)){
            String msg=equityNodeService.checkNodeStatus(id);
            if(StrUtil.isNotBlank(msg)){
                return ResultBean.error(msg);
            }
        }
        equityNode.setStatus(status);
        equityNodeService.save(equityNode);
        EquityTree equityTree = equityTreeService.get(equityNode.getTreeId());
        equityTree.setActiveStatus("2");
        equityTreeService.save(equityTree);
        return ResultBean.ok();
    }


    /**
     * 节点名允许重复，但是重复的节点对应的产品组必须一致
     * @param equityNodeVo
     * @return
     */
    public Boolean checkDate(EquityNodeVo equityNodeVo){
        EquityNode temp=new EquityNode();
        temp.setName(equityNodeVo.getName());
        temp.setDeleteStatus(0);
        Optional<EquityNode> equityTreeNodeOptional=equityNodeService.findOne(Example.of(temp));
        if(equityTreeNodeOptional.isPresent()){
            EquityNode equityNode=equityTreeNodeOptional.get();
            if(equityNodeVo.getId()!=null && equityNodeVo.getId() != equityNode.getId()){
                if(equityNodeVo.getGroupId()!=equityNode.getGroupId()){
                    return true;
                }
            }else if(equityNodeVo.getId()==null){
                if(!equityNodeVo.getGroupId().equals(equityNode.getGroupId())){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * <p><b>Title:</b> nodeAddHierarchy</p>
     * <p><b>Description:</b> 增加子节点,权益节点的层级增加 </p>
     *
     * @param  pcEquityNode
     *
     */
    public void nodeAddHierarchy(EquityNode pcEquityNode) {
        EquityNode temp = new EquityNode();
        temp.setTreeId(pcEquityNode.getTreeId());
        temp.setId(pcEquityNode.getParentId());
        EquityNode pcEquityNodeOpt = equityNodeService.findOne(temp);
        pcEquityNode.setHierarchy(pcEquityNodeOpt.getHierarchy() + 1);
    }


}
